package com.sdksoft.readcard

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import cn.mtjsoft.ocr_android.ScanningManager
import cn.mtjsoft.ocr_android.config.Config
import cn.mtjsoft.ocr_android.enums.ScanTypeEnum
import cn.mtjsoft.ocr_android.interfaces.ScanResultListener
import com.csht.bean.EPassportData
import com.csht.bean.IdCardData
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.ActivityNfcHuzhaoBinding
import com.csht.utils.HHTipUtils
import com.csht.utils.NfcUtils
import org.json.JSONObject
import java.util.*


class NFCHuZhaoActivity : BaseInitActivity(), ReadCardListener {
    //1.声明一个nfc的Adapter
    private lateinit var nfcUtils: NfcUtils

    private val TAG = "readcard"

    private lateinit var activityNfcHuzhaoBinding: ActivityNfcHuzhaoBinding

    private var isInitOk = false

    private val REQUEST_CODE = 1000

    override fun initView() {
        super.initView()
        setTitleText("护照读卡")
        activityNfcHuzhaoBinding = ActivityNfcHuzhaoBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply {
            addView(activityNfcHuzhaoBinding.root, 0)
        }
        activityNfcHuzhaoBinding.apply {
            btnOcr.setOnClickListener {
                readSettingBuilder.buildReadCardType(ReadCardType.NFC_PASSPORT)
                initSDK()
                mainHandler.postDelayed({
                    ocr()
                }, 500)
            }
            btnOcrPage.setOnClickListener {
                readSettingBuilder.buildReadCardType(ReadCardType.OCR_PASSPORT)
                initSDK()
                mainHandler.postDelayed({
                    readCardManager.readPassportStart(Intent(), "", "", "", this@NFCHuZhaoActivity)
                }, 500)
            }
        }
        nfcUtils = NfcUtils(this, this.javaClass)
        readSettingBuilder.buildReadCardType(ReadCardType.NFC_PASSPORT)
        initSDK()
    }

    /**
     * 初始化SDK
     */
    private fun initSDK() {
        readCardManager.readCardInit(object : InitListener {
            override fun onResponse(code: Int, msg: String) {
                when (code) {
                    StatusCode.ININ_ING.code -> {
                        Log.d(TAG, "初始化中. $msg")
                    }
                    StatusCode.ININ_OK.code -> {
                        isInitOk = true
                        runOnUiThread {
                            HHTipUtils.getInstance().showToast(this@NFCHuZhaoActivity, "初始化成功")
                        }
                    }
                    else -> {
                        isInitOk = false
                        runOnUiThread {
                            HHTipUtils.getInstance().showToast(this@NFCHuZhaoActivity, "初始化失败")
                        }
                    }
                }
            }
        })
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart")
        //此处adapter需要重新获取，否则无法获取message
        nfcUtils.nfcInit( this,  this.javaClass)
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume")
        //设置处理优于所有其他NFC的处理
        nfcUtils.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause")
        //恢复默认状态
        nfcUtils.onPause(this)
    }

    /**
     * OCR识别
     */
    private fun ocr() {
        activityNfcHuzhaoBinding.apply {
            ivHead.setImageResource(0)
            ScanningManager.instance.openScanningActivity(
                this@NFCHuZhaoActivity,
                Config(true, ScanTypeEnum.PASSPORT_MRZ, 1, 0, false, object : ScanResultListener {
                    override fun onSuccessListener(value: String?, bitmap: Bitmap?) {
                        value?.let {
                            try {
                                val jsonObject = JSONObject(it)
                                tvMsg.apply {
                                    text = "OCR识别成功--"
                                    append(System.currentTimeMillis().toString())
                                    append("\n")
                                    append("护照机读码：")
                                    append("\n")
                                    append(value)
                                    append("\n")
                                }
                                documentNumber.setText(
                                    jsonObject.optString(
                                        "documentNumber", ""
                                    )
                                )
                                dateOfBirth.setText(jsonObject.optString("dateOfBirth", ""))
                                dateOfExpiry.setText(jsonObject.optString("dateOfExpiry", ""))
                            } catch (e: Exception) {
                                tvMsg.text = e.message
                            }
                        }
                    }

                    override fun onFailureListener(error: String) {
                        tvMsg.text = error
                    }
                })
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (isInitOk.not()) {
            HHTipUtils.getInstance().showToast(this@NFCHuZhaoActivity, "没有初始化成功")
            return
        }
        activityNfcHuzhaoBinding.apply {
            val documentNumberStr = documentNumber.text.toString().trim().toUpperCase(Locale.ROOT)
            val dateOfBirthStr = dateOfBirth.text.toString().trim()
            val dateOfExpiryStr = dateOfExpiry.text.toString().trim()
            if (documentNumberStr.isEmpty() || dateOfBirthStr.isEmpty() || dateOfExpiryStr.isEmpty()) {
                HHTipUtils.getInstance().showToast(this@NFCHuZhaoActivity, "请完整填写参数")
                return@apply
            }
            HHTipUtils.getInstance()
                .showProgressDialog(this@NFCHuZhaoActivity, "读取中，请勿移动", false)
            // 开始读取护照
            readCardManager.readPassportStart(
                intent, documentNumberStr, dateOfBirthStr, dateOfExpiryStr, this@NFCHuZhaoActivity
            )
        }
    }

    override fun onReadCardState(type: Int, msg: String?) {
        if (type == StatusCode.READCARD_FAILE.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
            activityNfcHuzhaoBinding.tvMsg.text = "\n----------------------------\nstatus: $type  ，msg:$msg"
        } else if (type == StatusCode.READCARD_SUCCESS.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
        } else if (type == StatusCode.FIND_CARD_SUCCESS.code) {
            if (!HHTipUtils.getInstance().progressDialogIsShowing()) {
                HHTipUtils.getInstance().showProgressDialog(this, "正在读取,请勿移动", false)
            }
        }
    }

    override fun onReadICCardSuccess(icNumber: String?, type: Int) {
    }

    override fun onReadIDCardSuccess(bean: IdCardData?) {
    }

    override fun onReadPassportSuccess(bean: EPassportData?) {
        super.onReadPassportSuccess(bean)
//        activityNfcHuzhaoBinding.apply {
//            documentNumber.setText("")
//            dateOfBirth.setText("")
//            dateOfExpiry.setText("")
//        }
        HHTipUtils.getInstance().dismissProgressDialog()
        bean?.apply {
            activityNfcHuzhaoBinding.tvMsg.apply {
                text = "姓名："
                append(nameOfHolder)
                append(" / $primaryIdentifier $secondaryIdentifier")
                append("\n性别：")
                append(if (gender.startsWith("M")) "男" else "女")
                append(" / $gender")
                append("\n生日：")
                append(dateOfBirth)
                append("\n国家码：")
                append(nationality)
                append("\n有效期：")
                append(dateOfExpiry)
                append("\n护照号码：")
                append(documentNumber)
                append("\n个人号码：")
                append(personNumber)
                append("\n护照机读码：")
                append(mrz)
                if (passiveAuth) {
                    append("\n\npassiveAuthStr: pass")
                } else {
                    append("\n\npassiveAuthStr: failed")
                }
                if (chipAuth) {
                    append("\nchipAuthStr: pass")
                } else {
                    append("\nchipAuthStr: failed")
                }
                append("\n\n耗时：$duration ms")
            }
            if (image == null) {
                activityNfcHuzhaoBinding.ivHead.setImageResource(0)
            } else {
                image?.let {
                    val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                    activityNfcHuzhaoBinding.ivHead.setImageBitmap(bitmap)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HHTipUtils.getInstance().dismissProgressDialog()
        mainHandler.removeCallbacksAndMessages(null)
        readCardManager.readCardStop()
    }
}